var i = getApp(), s = i.requirejs("core"), foxui = i.requirejs("foxui");
// 引入SDK核心类
var QQMapWX = require("/../../utils/qqmap-wx-jssdk.min.js");

Page({
    data: {
        indicatorDotss: !0,
        autoplays: !0,
        intervals: 2e3,
        durations: 500,
        circulars: !0,
        beforeColor: "rbga(0,0,0,.5)",
        afterColor: "white",
        adveradmin: !0,
        current: 0,
        clock: "",
        shop: {},
        indicatorDots: !0,
        autoplay: !0,
        interval: 5e3,
        duration: 500,
        circular: !0,
        storeRecommand: [],
        total: 1,
        page: 1,
        loading: false,
        loaded: false,
        indicatorDotsHot: !1,
        autoplayHot: !0,
        intervalHot: 5e3,
        durationHOt: 1e3,
        circularHot: !0,
        specs: [],
        options: [],
        diyform: {},
        specsTitle: "",
        bannerImg: [],
        selfList: [],
        showothers: 0,
        showvideos: 0,
        open_creditshop: 0,
        merchid: 0,
        merch: [],
        keywords: "",
        goods_title: "",
        goods_subtitle: "",
        result: {
            bannerheight: ""
        },
        cate: 0,
        cate_list: [],
        exceed: 0,
        distance: 0,
    },
    onLoad: function(t) {
        var merchid = 0;
        if(t.merchid) merchid = t.merchid, console.log(t);
        if(t.scene){
            var p = decodeURIComponent(t.scene);
            var scene = s.str2Obj(p);
            merchid = scene.merchid;
        }
        t = t || {};
        var a = this;
        if(merchid) {
            a.setData({
                imgUrl: i.globalData.approot,
                merchid: merchid
            })
        }else {
            a.setData({
                imgUrl: i.globalData.approot,
            })
        }
        s.get("black", {}, function(t) {
            t.isblack && wx.showModal({
                title: "无法访问",
                content: "您在商城的黑名单中，无权访问！",
                success: function(t) {
                    t.confirm && a.close(), t.cancel && a.close();
                }
            });
        });
        var e = decodeURIComponent(t.scene);
        if (!t.id && e) {
            var n = s.str2Obj(e);
            t.id = n.id, n.mid && (t.mid = n.mid, i.setCache("usermid", n));
        }
        a.getBanner(),
        a.getRecommand(),
        wx.getSystemInfo({
          success: function(t) {
                var e = t.windowWidth / 1.5;
                a.setData({
                    swiperheight: e
                });
            }
        });
    },
    onShow: function() {
        var t = this, a = wx.getSystemInfoSync(), e = i.getCache("sysset");
		wx.getSetting({
            success: function(a) {
                var e = a.authSetting["scope.userInfo"];
                t.setData({
					limits: e,
					imgUrl: i.globalData.approot
                });
            }
        });
        i.getCache("isIpx") ? t.setData({
            isIpx: !0,
            iphonexnavbar: "fui-iphonex-navbar",
            paddingb: "padding-b"
        }) : t.setData({
            isIpx: !1,
            iphonexnavbar: "",
            paddingb: ""
        })
        t.menuButtonObject();
    },
    menuButtonObject: function() {
        var e = this;
        // 根据不同机型计算距离顶部距离
        let menuButtonObject = wx.getMenuButtonBoundingClientRect();
        wx.getSystemInfo({
          success: res => {
            let statusBarHeight = res.statusBarHeight,
                navTop = menuButtonObject.top, // 胶囊按钮与顶部的距离
                navHei = menuButtonObject.height, // 胶囊高度
                navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2; // 导航高度
            e.data.navHeight = navHeight;
            e.data.navTop = navTop;
            e.data.windowHeight = res.windowHeight;
            navTop = navTop + navHei + 10;
            e.setData({ top: navTop })
          },
          fail(err) {
            console.log(err);
          }
        })
    },
    onReachBottom: function() {
        if(this.data.page != 1)
        this.data.loaded || this.data.storeRecommand.length == this.data.total || this.getRecommand();
    },
    getRecommand: function() {
        var t = this;
        t.setData({
            loading: true
        }), s.get("shop/get_merchgoods", {
            cate: t.data.cate,
            merchid: t.data.merchid,
            page: t.data.page,
            keywords: t.data.keywords,
        }, function(a) {
            // var e = {
            //     loading: !1,
            //     total: a.total
            // };
            // t.setData({
            //     loading: !1,
            //     total: a.total,
            //     show: !0,
            // }),
            // a.list || (a.list = []), a.list.length > 0 && (t.setData({
            //     storeRecommand: t.data.storeRecommand.concat(a.list),
            //     page: a.page + 1
            // }), a.list.length < a.pagesize && (e.loaded = !0));
            var i = {
                loading: false,
                total: a.total,
                pagesize: a.pagesize,
                show: !0
            };
            a.list.length > 0 && (i.page = t.data.page + 1, i.storeRecommand = t.data.storeRecommand.concat(a.list), 
            a.list.length < a.pagesize && (i.loaded = true)), t.setData(i);
        });
    },
    getBanner: function() {
        var t = this;
        s.get("shop/get_home", {
            merchid: t.data.merchid,
            page: t.data.page
        }, function(a) {
            t.setData({
                wmopen: a.wmopen,
                qzlogin: a.qzlogin,
                bannerImg: a.advs,
                cate_list: a.cate_list,
                showothers: a.showothers,
                showvideos: a.showvideos,
                open_creditshop: a.open_creditshop,
                merch: a.merch,
                goods_title: a.goods_title,
                goods_subtitle: a.goods_subtitle,
            }), t.qzlogin(), 
            t.findShop();
            // t.getLocation();
        });
    },
    getLocation: function (){
        var that = this;
        wx.getLocation({
            type: "gcj02",
            success: function(res) {
                const distance_new = that.getDistance(res.latitude, res.longitude, that.data.merch.lng, that.data.merch.lat);
                console.log(distance_new);
            },
            fail: function(res) { 
                wx.showModal({
                    title: "提示",
                    content: "请打开位置信息，定位商家距离！",
                    showCancel: false,
                    confirmText: "确定",
                    success: (data) => {
                        if (data.confirm) {
                            // wx.reLaunch({
                            //     url: "/pages/index/index?merchid=0",
                            // })
                        }
                    }
                })
            }
        })
    },
    getDistance(lat1, lng1, lat2, lng2) {
        var radLat1 = lat1 * Math.PI / 180.0;
        var radLat2 = lat2 * Math.PI / 180.0;
        var a = radLat1 - radLat2;
        var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;
        s = Math.round(s * 10000) / 10000;
        if(s>1) this.setData({ exceed: 1, distance: s, });
        s = s.toFixed(2) + "km"
        return s
    },
    findShop() { 
        // 拿到商家的地理位置，用到了腾讯地图的api
        // 实例化API核心类
        var _that = this
        var demo = new QQMapWX({
            key: "CZBBZ-CBNCW-IGAR3-O4P4Z-BF4WZ-IIF4E"
        });
        demo.calculateDistance({
            to: [{
                latitude: _that.data.merch.lng,     // 商家的纬度
                longitude: _that.data.merch.lat,    // 商家的经度
            }],
            success: function(res) {
                // 拿到距离(米)
                let hw = res.result.elements[0].distance;
                // 拿到正确的值
                if (hw && hw !== -1) {
                    if((hw / 2 / 500).toFixed(2)>1) _that.setData({ exceed: 1, distance: hw, });
                    // 转换成公里
                    hw = (hw / 2 / 500).toFixed(2) + "km"
                } else {
                    hw = "距离太近或请刷新重试"
                }
                // s.alert(hw);
                // console.log("腾讯地图计算距离商家" + hw);
            }
        });
    },
    qzlogin: function() {
        var _t = this, qzlogin = _t.data.qzlogin, 
            userinfoOpenid = i.getCache("userinfo_openid");
        if(qzlogin==1){
            if(!userinfoOpenid) wx.navigateTo({ url: "/pages/auth/index", })
        }
    },
    imagesHeight: function(t) {
        var a = t.detail.width, e = t.detail.height, i = t.target.dataset.type, s = this;
        wx.getSystemInfo({
            success: function(t) {
				s.data.result[i] = t.windowWidth / a * e, 
				(!s.data[i] || s.data[i] && result[i] < s.data[i]) && s.setData({
                    result: s.data.result
				});
            }
        });
    },
    bindSearch: function(p) {
        this.setData({
            storeRecommand: [],
            page: 1,
            loaded: false,
            keywords: p.detail.value,
        })
        ,this.getRecommand();
    },
    cate: function(p) {
        var cate = p.currentTarget.dataset.type;
        this.setData({
            storeRecommand: [],
            page: 1,
            cate: cate,
            loaded: false,
        })
        ,this.getRecommand();
    },
    url: function(p) {
        var url = "", userinfoOpenid = i.getCache("userinfo_openid");
        if(userinfoOpenid) url = p.currentTarget.dataset.url;
        else url = "/pages/auth/index"
        wx.navigateTo({ url: url, })
    },
    storeUrl: function(p) {
        var wmopen = this.data.wmopen,
            type = p.currentTarget.dataset.type,
            url = p.currentTarget.dataset.url;
        if(wmopen==1 && type==2){
            // wx.showToast({
            //     title: "敬请期待",
            //     icon: "none",
            //     duration: 1500
            // })
            s.alert("敬请期待");
        }else{
            wx.navigateTo({ url: url, })
        }
    },
    alertUrl: function() {
        s.alert("超出一公里，请至同城配送下单");
    },
    urlreLaunch: function(p) {
        i.removeCache("merchid");
        var url = p.currentTarget.dataset.url;
        wx.reLaunch({ url: url, })
    },
    call: function(p) {
        let phone = p.currentTarget.dataset.tel;
        wx.makePhoneCall({
          phoneNumber: phone,
          success:function() { console.log("成功！"); },
          fail:function() { console.log("失败！"); return }
        })
    },
    loca: function (p) {
        let dataset = p.currentTarget.dataset,
            lat = parseFloat(dataset.lat), lng = parseFloat(dataset.lng), 
            nme = dataset.name, add = dataset.address;
        wx.openLocation({
          latitude: lat,
          longitude: lng,
          name: nme,
          address: add
        })
    },
    bindInput: function(t) {
        this.setData({
            inputValue: t.detail.value
        });
    },
});